package cn.earl.springboot.user.controller;

import java.io.File;
import java.io.IOException;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Locale;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.MessageSource;
import org.springframework.context.i18n.LocaleContextHolder;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import cn.earl.springboot.entity.Global;
import cn.earl.springboot.entity.ResponseMessage;
import cn.earl.springboot.entity.User;
import cn.earl.springboot.user.service.UserService;

@RestController
@RequestMapping("/user")
public class UserController {

	private Logger logger = Logger.getLogger(UserController.class);

	/**
	 * 在RestController下设置方法返回值为ModelAndView可以返回页面
	 */

	@Autowired // 有多个UserService实现类时，需要使用@Qualifier或者@Resource区分
	private UserService userService;
	@Autowired
	private MessageSource messageSource;

	/**
	 * 校验手机号码，发送验证码
	 * 
	 * @param phoneNumber
	 * @param request
	 * @return
	 */
	@RequestMapping("/verify")
	public ResponseMessage verify(String phoneNumber, HttpServletRequest request) {
		String regExp = "^((13[0-9])|(15[^4])|(18[0,2,3,5-9])|(17[0-8])|(147))\\d{8}$";
		Pattern p = Pattern.compile(regExp);
		Matcher m = p.matcher(phoneNumber); 
		//或者直接match(String regex)-boolean
		if (!m.matches()) {// 手机格式验证不正确
			return new ResponseMessage<>(400, "号码格式不正确");
		}
		try {
			/**
			 * 发送验证码 List list = MobileCheck.sendMessage(phoneNumber);
			 */
			// 已经验证可以发送数据了
			// 现在使用假的数据来测试异常操作
			int fakeCode = (int) (Math.random() * 1000000);
			List<String> list = new ArrayList<>();
			list.add("0");
			list.add("" + fakeCode);
			System.out.println("生成的随机码为--->" + fakeCode);

			if (!"0".equals(list.get(0))) {
				return new ResponseMessage<>(400, "发送失败");
			}
			String code = (String) list.get(1);
			SimpleDateFormat sdf = new SimpleDateFormat(Global.DATE_FORMAT);
			String sendTime = sdf.format(new Date());
			// 保存验证码和发送时间
			List<String> attrList = new ArrayList<>();
			// attrList.add(code);
			attrList.add(code + "");
			attrList.add(sendTime);
			request.getSession().setAttribute(phoneNumber, attrList);
			return new ResponseMessage<>(250, "发送成功");

		} catch (Exception e) {
			e.printStackTrace();
			return new ResponseMessage<>(400, "请重新发送验证");
		}
	}

	/**
	 * 注册
	 * 
	 * @param user
	 * @param request
	 * @return
	 */
	@RequestMapping("/regist")
	public ResponseMessage regist(@Validated User user, BindingResult bindingResult, HttpServletRequest request) {

		if (bindingResult.hasErrors()) {
			// 错误信息提示
			StringBuffer error = new StringBuffer();

			// 获得错误字段集合
			List<FieldError> fieldErrors = bindingResult.getFieldErrors();
			// 获得本地local,zh_CN
			Locale locale = LocaleContextHolder.getLocale();

			for (FieldError fe : fieldErrors) {
				// 遍历错误提示
				String message = messageSource.getMessage(fe, locale);
				// System.out.println(fe.getField() + "-->" + message);
				error.append(fe.getField() + "：" + message);
			}
			return new ResponseMessage<>(200, error.toString());
		}

		/**
		 * 校验注册码<br>
		 * list中保存的<br>
		 * 第一个是手机号对应的验证码<br>
		 * 第二个是发送验证码的时间
		 */
		List attrList = (List) request.getSession().getAttribute(user.getPhone_number());
		if (attrList == null) {
			return new ResponseMessage<>(260, "手机号码未填或未验证");
		}
		if (attrList.size() > 0) {
			// 验证码不匹配
			if (!user.getCode().equals(attrList.get(0))) {
				return new ResponseMessage<>(300, "验证码不正确");
			}
			// 超过验证码限定时间
			// yyyy-MM-dd HH:mm:ss
			String sendTimeStr = (String) attrList.get(1);
			DateFormat df = new SimpleDateFormat(Global.DATE_FORMAT);
			Date sendTime;
			try {
				sendTime = df.parse(sendTimeStr);
			} catch (ParseException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
				return new ResponseMessage<>(351, "请重新发送一次验证码");
			}
			Date now = new Date();
			long start = sendTime.getTime();
			long end = now.getTime();
			long gap = end - start;
			if (gap / 60000 > 5) {// 超时
				return new ResponseMessage<>(352, "验证码已过期，请重新发送");
			}

		} else {
			return new ResponseMessage<>(300, "需要进行手机号码验证");
		}

		// 设置注册时间，保存用户
		user.setRegist_date(new Date());
		user.setCredit(10);
		user.setRevocation(3);
		user.setStatus(true);
		userService.saveUser(user);
		// 防止重复登陆
		// ServletContext application =
		// request.getSession().getServletContext();
		// application.setAttribute(user.getUsername(), user.getUsername());

		return new ResponseMessage<>(250, "注册成功");
	}

	/**
	 * 登陆
	 * 
	 * @param username
	 *            用户名或者手机号码
	 * @param password
	 * @param request
	 * @return
	 */
	@PostMapping("/login")
	public ResponseMessage<User> login(@RequestParam String username, @RequestParam String password,
			HttpServletRequest request) {

		User user = userService.findUserByUsernameOrPhoneNumberAndPassword(username, password);

		if (user == null) {
			return new ResponseMessage<>(200, "用户不存在");
		}
		// 验证重复登陆
		// ServletContext application =
		// request.getSession().getServletContext();
		// String usernameStr = (String) application.getAttribute(user.getId() +
		// "");
		// if (usernameStr != null) {
		// // 重复登陆
		// return new ResponseMessage<>(200, "重复登陆");
		// } else {
		// application.setAttribute(user.getId() + "", username);
		// }
		logger.info(user.getId() + " 用户登录！");
		return new ResponseMessage<>(250, "登陆成功", user);
	}

	/**
	 * 注销登陆
	 * 
	 * @param id
	 * @param request
	 * @return
	 */
	@RequestMapping("/signout")
	public ResponseMessage signout(@RequestParam int id, HttpServletRequest request) {
		ServletContext application = request.getSession().getServletContext();
		application.removeAttribute(id + "");
		return new ResponseMessage<>(250, "退出成功");
	}

	/**
	 * 修改头像
	 * 
	 * @param picture
	 * @param id
	 * @param request
	 * @return
	 * @throws IOException 
	 * @throws IllegalStateException 
	 */
	@RequestMapping("/updateAvatar")
	public ResponseMessage updateAvatar(@RequestParam MultipartFile picture, @RequestParam int id,
			HttpServletRequest request) throws IllegalStateException, IOException {

		if (!picture.isEmpty()) {
			// path=/user/updateAvatar
			// String path = request.getServletPath();
			// System.out.println("path=" + path);

			// C:\Users\ASUS-A455L\AppData\Local\Temp\tomcat-docbase.1996969919573372972.8080\
			// String realPath =
			// request.getSession().getServletContext().getRealPath("/");
			// System.out.println("realPath="+realPath);

			// String originalFilename = picture.getOriginalFilename();
			// System.out.println("originalFilename=" + originalFilename);

			// 为空，springboot没有布置项目名
			// String contextPath = request.getContextPath();
			// System.out.println(contextPath);
			
			//保存文件
			picture.transferTo(new File("F://youzhu_picture_temp/"+picture.getOriginalFilename()));

			return new ResponseMessage<>(250, "修改成功");
		} else {
			return new ResponseMessage<>(405, "图片不能为空");

		}

	}

	public ResponseMessage confirmUserStatus(String username) {
		boolean status = userService.confirmUserStatus(username);
		if (status) {
			return new ResponseMessage<>(250, "用户身份合法");
		} else {
			return new ResponseMessage<>(300, "用户身份不合法");
		}
	}

	// @RequestMapping("/testCode")
	// public ResponseMessage testCode(String number,HttpServletRequest
	// request){
	// HttpSession session = request.getSession();
	// List<String> list = new ArrayList<>();
	// int a = (int)(Math.random()*1000000);
	// list.add(a+"");
	// list.add(new java.util.Date().toString());
	// session.setAttribute(number,list );
	// List attrList = (List) session.getAttribute(number);
	// for(Object s:attrList){
	// System.out.println("......."+s);
	// }
	//
	// return new ResponseMessage(300,"用户身份不合法："+a,null);
	// }

}
